package mobao.system.token;

import mobao.baseinfo.user.entity.SysUserT;
import mobao.system.exception.MobaoException;
import mobao.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.security.auth.message.AuthException;
import javax.servlet.http.HttpServletRequest;

import static mobao.system.intercepter.AuthorizationInterceptor.USER_KEY;

@Component
public class AuthManager {

    @Autowired
    private TokenManager tokenManager;
    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 获取请求体
     * @return
     */
    public HttpServletRequest getRequest(){
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * 登录
     * @param userInfo
     * @return
     */
    public String signIn(SysUserT userInfo){
        return tokenManager.getToken(userInfo);
    }

    /**
     * 获取该访问用户信息
     * @return
     */
    public SysUserT getUserInfo() throws AuthException {
        HttpServletRequest request=getRequest();
        SysUserT userInfo = null;
        userInfo = (SysUserT)request.getAttribute(USER_KEY);
        if(userInfo != null){
            return userInfo;
        }
        String token=request.getHeader(jwtUtils.getHeader());
        if(token == null){
            throw new MobaoException("无token信息!", HttpStatus.UNAUTHORIZED.value());
        }
        userInfo=tokenManager.getUserInfoByToken(token);
        if(userInfo==null){
            throw new MobaoException("当前token已过期!", HttpStatus.UNAUTHORIZED.value());
        }
        return userInfo;
    }

    /**
     * 刷新该登录用户，延时
     */
    public void refreshUserInfo(){
        HttpServletRequest request=getRequest();
        String token=request.getHeader(jwtUtils.getHeader());
        if(token == null){
            throw new MobaoException("无token信息!", HttpStatus.UNAUTHORIZED.value());
        }
        tokenManager.refreshUserToken(token);
    }

    /**
     * 注销该访问用户
     */
    public void loginOff(){
        HttpServletRequest request=getRequest();
        String token=request.getHeader(jwtUtils.getHeader());
        if(token == null){
            return;
        }
        tokenManager.loginOff(token.toString());
    }

    public JwtUtils getJwtUtils() {
        return jwtUtils;
    }
}